<template>
    <el-container>
        <el-header>
            <div><img src="../../pictures/logo.png" width="68px" height="60px"> <span>科记：记录精彩校园生活</span></div>
            <el-menu
            :default-active="activeIndex2"
            class="el-menu-demo"
            mode="horizontal"
            background-color="#99ecff"
            text-color="black"
            active-text-color="#f59456">
                <el-menu-item class="grid-content" index="1">
                    <el-link href="#/home" target="_self" underline="false">科记主页</el-link>
                </el-menu-item>
                <el-submenu class="grid-content" index="3">
                    <template slot="title">生活助手</template>
                    <el-menu-item index="3-1">
                        <router-link :to="{ name: 'blog', params: { id: 1 } }">校园博客</router-link>
                    </el-menu-item>
                    <el-menu-item index="3-2">
                        <router-link :to="{ name: 'blog', params: { id: 2 } }">生活分享</router-link>
                    </el-menu-item>
                    <el-menu-item index="3-3"><a href="#/question" target="_self">校园问答</a></el-menu-item>
                </el-submenu>
                <el-submenu class="grid-content" index="4">
                    <template slot="title">班级事务</template>
                    <el-menu-item index="4-1">
                        <router-link :to="{ name: 'notice'}">班级通知</router-link>
                    </el-menu-item>
                    <el-menu-item index="4-2"><a href="#/account" target="_self">班级账目</a></el-menu-item>
                </el-submenu>
                <el-menu-item class="grid-content" index="5">
                    <el-link href="#/information" target="_self" underline="false">个人信息</el-link>
                </el-menu-item>
                <el-menu-item class="grid-content">
                    <div display: center>
                        <el-input placeholder="请输入内容" v-model="input3" class="input-with-select">
                            <el-select v-model="select" slot="prepend" placeholder="请选择">
                            <el-option label="校园博客" value="1"></el-option>
                            <el-option label="生活助手" value="2"></el-option>
                            <el-option label="校园问答" value="3"></el-option>
                            <el-option label="班级通知" value="4"></el-option>
                            </el-select>
                            <el-button slot="append" icon="el-icon-search"></el-button>
                        </el-input>
                    </div>
                </el-menu-item>
                <el-menu-item>
                    <div><el-col :span="12">
                            <div class="demo-basic--circle">
                                <div class="block"><el-avatar shape="square" :size="50" :src="squareUrl"></el-avatar></div>
                            </div>
                        </el-col> 
                    </div>
                </el-menu-item>
            </el-menu>
            <div class="line"></div>
        </el-header>

        <el-main>
            <el-table
            :data="tableData"
            height="250"
            border
            style="width: 100%">

                <el-table-column
                prop="eventDate"
                label="日期"
                width="180">
                <template slot-scope="scope">
                    <el-input v-if="isEditing && editingId === scope.row.id" v-model="scope.row.eventDate" type="date"></el-input>
                    <span v-else>{{ scope.row.eventDate }}</span>
                </template>
                </el-table-column>

                <el-table-column
                prop="coordinator"
                label="发布人"
                width="180">
                <template slot-scope="scope">
                    <el-input v-if="isEditing && editingId === scope.row.id" v-model="scope.row.coordinator"></el-input>
                    <span v-else>{{ scope.row.coordinator }}</span>
                </template>
                </el-table-column>

                <el-table-column
                prop="totalCost"
                label="金额"
                width="180">
                <template slot-scope="scope">
                    <el-input v-if="isEditing && editingId === scope.row.id" v-model="scope.row.totalCost"></el-input>
                    <span v-else>{{ scope.row.totalCost }}</span>
                </template>
                </el-table-column>

                <el-table-column
                prop="costSource"
                label="资金来源"
                width="180">
                <template slot-scope="scope">
                    <el-input v-if="isEditing && editingId === scope.row.id" v-model="scope.row.costSource"></el-input>
                    <span v-else>{{ scope.row.costSource }}</span>
                </template>
                </el-table-column>

                <el-table-column
                prop="eventName"
                label="活动名称">
                <template slot-scope="scope">
                    <el-input v-if="isEditing && editingId === scope.row.id" v-model="scope.row.eventName"></el-input>
                    <span v-else>{{ scope.row.eventName }}</span>
                </template>
                </el-table-column>

                <el-table-column
                prop="id"
                label="账单id">
                </el-table-column>

                <el-table-column
                prop="classCode"
                label="班级编号"
                width="180">
                </el-table-column>

                <el-table-column
                    label="操作">
                    <template slot-scope="scope">
                        <el-button v-if="!isEditing" type="text" @click="startEdit(scope.row.id)">修改</el-button>
                        <el-button v-if="isEditing && editingId === scope.row.id" type="text" @click="saveEdit(scope.row)">保存</el-button>
                        <el-button type="text" @click="confirmDelete(scope.row.id)">删除</el-button> <!-- 增加删除按钮 -->
                    </template>
                </el-table-column>
            </el-table>
        </el-main>
    </el-container>
</template>

<script>
    
    import { deleteClassbill } from '@/api/account.js'
    import { uploadClassbill } from '@/api/account.js'
    import { checkClassbill } from '@/api/account.js'
    import { getUsersinfo } from '@/api/account.js'

    export default {
    data() {
      return {
        activeIndex: '1',
        activeIndex2: '1',//与字体颜色有关的值
        input: '',//搜索栏的输入
        select: '',//搜索栏的选择
        squareUrl: "https://cube.elemecdn.com/9/c2/f0ee8a3c7c9638a54940382568c9dpng.png",//头像的访问路径
        tableData: [],
        accountId: '',
        isEditing: false, // 编辑状态
        editingId: null, // 当前正在编辑的账目ID
        searchForm: {
            id: '',
            classCode: '',
            eventName: '',
            eventDate: '',
            totalCost:'',
            costSource: '',
            coordinator: '',
        }
      };
    },
    
    methods: {
        async fetchUserInfo() {
            try {
                const response = await getUsersinfo();
                if (response.data.code === 0) {
                    alert('获取用户信息失败，请重新登录');
                    window.location.href = '#/login';
                    return false;
                } else { // 更新用户信息
                    localStorage.setItem('classCode', response.data.data.classCode);
                    if (response.data.data.imageUrl) {
                        this.squareUrl = response.data.data.imageUrl;
                    }
                }
            } catch (error) {
                console.error("获取用户信息失败:", error);
                alert('请求失败，请稍后重试');
            }
        },

        async fetchClassbill() {
            try {
                this.classCode = localStorage.getItem('classCode');
                const response = await checkClassbill(this.classCode);
                if (response.data.code === 0) {
                    console.log(response.data.code);
                    alert('获取班级账目失败，当前账户无权限，请联系管理员');
                    window.location.href = '#/login';
                    return false;
                } else { // 更新班级账目
                    this.tableData = response.data.data;
                }
            } catch (error) {
                console.error("获取班级账目失败:", error);
                alert('请求失败，请稍后重试');
            }
        },

        confirmDelete(id) {
            this.$confirm('确定要删除该账目吗?', '提示', {
                confirmButtonText: '确定',
                cancelButtonText: '取消',
                type: 'warning'
            }).then(() => {
                this.deleteClassbill(id); // 调用删除方法
            }).catch(() => {
                this.$message({
                    type: 'info',
                    message: '已取消删除'
                });
            });
        },
        
        deleteClassbill(id) {
            deleteClassbill(id).then(response => {
                if (response.data.code === 0) {
                    alert('删除账目失败，当前账户无权限，请联系管理员');
                    return false;
                } else { // 更新班级账目
                    alert('删除账目成功');
                    this.fetchClassbill(); // 重新获取账单数据
                }
            }).catch(error => {
                console.error("删除账目时出错:", error);
                alert('请求失败，请稍后重试');
            });
        },

        startEdit(id) {
            this.isEditing = true;
            this.editingId = id; // 设置当前正在编辑的账目ID
        },
        saveEdit() {  
            // 找到当前正在编辑的数据
            const updatedRow = this.tableData.find(item => item.id === this.editingId);
            this.accountId = updatedRow.id; // 设置当前正在编辑的账目ID
            const dataToSend = {
                classCode: updatedRow.classCode,
                eventName: updatedRow.eventName,
                eventDate: updatedRow.eventDate,
                totalCost: updatedRow.totalCost,
                costSource: updatedRow.costSource,
                coordinator: updatedRow.coordinator,
            };

            uploadClassbill(this.accountId,JSON.stringify(dataToSend)).then(response => {
                if(response.data.code === 0) {
                    alert('修改账目失败，当前账户无权限，请联系管理员');
                    return false;
                } else { // 更新班级账目
                    alert('修改账目成功');
                    this.isEditing = false; // 退出编辑模式
                    this.editingId = null; // 重置编辑ID
                    this.fetchClassbill();
                } 
            })
        }
    },

    mounted() {
        this.fetchUserInfo().then(() => { // 在获取用户信息成功之后执行获取班级账单
            this.fetchClassbill();
        });
    }
  }
</script>

<style>
    .el-header{
        background: #99ecff;
        display: flex;
        padding-left: 0;
        justify-content: space-between;
        color: black;
        font-size: 20px;
        > div{
            display: flex;
            align-items: center;
            span{
                margin-left: 15px;
            }
        }
    }
    .el-select .el-input {
        width: 130px;
    }
    .input-with-select .el-input-group__prepend {
        background-color: #fff;
    }
    
</style>